<template>
  <div>
    <el-form ref="form" :model="user" :rules="rules" label-width="80px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="user.nickName" maxlength="30" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input v-model="user.phoneNumber" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="user.email" maxlength="50" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="user.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" size="mini" @click="submit">修改信息</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
import { recordLog } from '@/api/recordLog'

export default {
  name: 'UserDetails',
  data() {
    return {
      user: {
        id: this.$store.getters.id,
        nickName: this.$store.getters.nickName,
        phoneNumber: this.$store.getters.phoneNumber,
        email: this.$store.getters.email,
        gender: this.$store.getters.gender
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phoneNumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          updateUserProfile(this.user).then(response => {
            this.$store.dispatch('user/getInfo')
            this.$message({
              message: '修改成功',
              type: 'success',
              center: true
            })
            recordLog({ username: this.$store.getters.username, operate: '修改个人信息' })
          })
        }
      })
    }
  }
}
</script>
